// 用户模块
import storage from '@/utils/storage.js'
import { ACCESS_TOKEN, CURRENT_USER } from '@/store/mutationTypes.js'
import user from '@/api/user/user.js'

const state = {
  token: storage.get(ACCESS_TOKEN) || '',
  userInfo: storage.get(CURRENT_USER) || {},
  roles: []
}

const mutations = {
  setUserInfo: (state, userInfo) => {
    state.userInfo = userInfo
  },
  setToken: (state, token) => {
    state.token = token
  },
  clearUserInfo: (state) => {
    state.userInfo = {}
    state.token = ''
  },
  setRoles: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // 登录
  login: async ({ commit }, userInfo) => {
    // console.log(userInfo)
    try {
      const response = await user.login(userInfo)
      if (response) {
        storage.set(ACCESS_TOKEN, response.token)
        storage.set(CURRENT_USER, response)
        // storage.set(ROLES, [response.role])
        commit('setToken', response.token)
        commit('setUserInfo', response)
        // commit('setRoles', [response.role])
        return Promise.resolve(response)
      }
    } catch (e) {
      return Promise.reject(e)
    }
  },
  // 退出登录
  loginOut: ({ commit }) => {
    storage.clear()
    storage.clearCookie()
    commit('clearUserInfo')
    commit('setRoles', [])
  }
}

const getters = {
  token: (state) => state.token,
  userInfo: (state) => state.userInfo,
  roles: (state) => state.roles
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
